package com.gome.postwoman;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gome.vue4j.core.AbstractVue4jComponent;
import com.gome.vue4j.core.FXMLPath;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

@FXMLPath("/postwoman-view.fxml")
public class PostWomanView extends AbstractVue4jComponent {
    private static final  org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(WSServer.class);

    public PostWomanView(){
        historyList = Store.getHistory();
        favorites = Store.getFavorites();
    }

    @FXML
    StringProperty url = new SimpleStringProperty("ws://127.0.0.1:11219");

    @FXML
    StringProperty receiveMessage = new SimpleStringProperty("");

    @FXML
    void receiveMessageClean(){
        receiveMessage.set("");
    }

    @FXML
    StringProperty sendMessage = new SimpleStringProperty("");

    @FXML
    StringProperty notice = new SimpleStringProperty("");

    @Override
    public void created() {
        notice.addListener((observableValue, old, newText) -> {
            if(newText != null && newText.length() != 0){
                //延迟清除
                Timer timer = new Timer();
                timer.schedule(new TimerTask(){
                    public void run(){
                        notice.set("");
                        timer.cancel();
                    }
                },3000);

            }
        });
    }

    @FXML
    void send(){
        String text = sendMessage.get();
        if(null == text || text.length() == 0){
            notice.set("消息为空.");
            return;
        }

        if(client == null){
            notice.set("未连接到服务器.");
            return;
        }

        client.send(text);
    }

    @FXML
    void format(){
        String json = sendMessage.get();
        if(json != null && json.length() > 0){
            JSONObject object;
            try {
                object = JSON.parseObject(json);
            }catch (Exception e){
                notice.set("不能格式化非JSON字符串");
                return;
            }

            String text = JSON.toJSONString(object, SerializerFeature.PrettyFormat,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteNullListAsEmpty);
            sendMessage.set(text);
        }
    }

    @FXML
    public WebSocketClient client = null;

    @FXML
    void conn(){
        connClose();
        WebSocketClient client;
        try {
            client = new WebSocketClient(new URI(url.get())){

                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    if (!historyList.contains(url.get())) {
                        historyList.add(url.get());
                        Store.update();
                    }

                    receiveMessage.set(String.format("\n\r [%s] (连接到服务器) %s ",new Date(),receiveMessage.get()));
                }

                @Override
                public void onMessage(String s) {
                    receiveMessage.set(String.format("\n\r [%s] (收到) %s %s ",new Date(),s,receiveMessage.get()));
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    receiveMessage.set(String.format("\n\r [%s] (关闭连接) %s ",new Date(),receiveMessage.get()));
                }

                @Override
                public void onError(Exception e) {
                    receiveMessage.set(String.format("\n\r [%s] (发生错误) %s %s ",new Date(),e.getMessage(),receiveMessage.get()));
                }
            };
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }

        client.connect();
        this.client = client;
        update();
    }

    @FXML
    void connClose(){
        if (client != null) {
            try {
                client.close();
            }catch (Exception e){
                log.error("关闭ws出错",e);
            }
            client = null;
        }
        update();
    }

    @FXML
    StringProperty favoriteName = new SimpleStringProperty();

    //消息收藏夹
    @FXML
    public Map<String,String> favorites;

    @FXML
    void favorite(){
        String key = favoriteName.get();
        String value = sendMessage.get();
        if(key != null && value != null && value.length() != 0 && key.length() != 0){
            favorites.put(key,value);
            update();
            Store.update();
        }
    }

    @FXML
    void removeFavorite(Event event){
        Button button = (Button) event.getSource();
        String key = button.getUserData().toString();
        favorites.remove(key);
        update();
    }

    @FXML
    void selectFavorite(Event event){
        Button button = (Button) event.getSource();
        String key = button.getUserData().toString();
        String value = favorites.get(key);

        sendMessage.set(value);
    }

    boolean historyFlag = false;

    @FXML
    void historyToggle(){
        historyFlag = !historyFlag;
        update();
    }

    @FXML
    public List<String> historyList;

    @FXML
    void removeHistory(Event event){
        Button button = (Button) event.getSource();
        int index = Integer.parseInt(button.getUserData().toString());
        historyList.remove(index);
        update();
    }

    @FXML
    void selectHistory(Event event){
        Button button = (Button) event.getSource();
        int index = Integer.parseInt(button.getUserData().toString());
        String uri = historyList.get(index);

        url.set(uri);
    }
}
